<template>
  <div>
    <el-dialog
      v-model="addFormVisible"
      title="添加角色"
      :append-to-body="true"
      @close="closeDialog"
      :destroy-on-close="true"
    >
      <el-form
        class="addroleform"
        :model="addRoleForm"
        :rules="addFormRule"
        ref="roleform"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input ref="rolename" v-model="addRoleForm.name"></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="addRoleForm.isDefault" label="默认"></el-checkbox>
          <el-tooltip
            class="item"
            effect="dark"
            content="新用户默认拥有此角色"
            placement="top"
          >
            <i class="el-icon-info"></i>
          </el-tooltip>
        </el-form-item>
      </el-form>

      <div class="modal-footer">
        <el-button type="primary" @click="saveRole">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { addRole } from "@/api/identity/role/index";
import { RoleItemAdd } from "@/api/identity/role/types";
import { FormRules, FormInstance } from "element-plus";
const props = defineProps({
  FormVisible: { type: Boolean, default: false },
});
const emit = defineEmits(["closedialogevent","refresh"]);
const addFormVisible = ref<boolean>(false);

const addFormRule: FormRules = reactive({
  name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
});
const addRoleForm = reactive<RoleItemAdd>({
  name: "",
  isDefault: false,
  isPublic: false,
});

const roleform = ref<FormInstance>();


function saveRole() {
  roleform.value?.validate((valid, fields) => {
    if (valid) {
   
      addRole(addRoleForm).then((res) => {
        if (res) {
          ElNotification({
            title: '提示',
            message: '添加角色成功',
            type: "success",
            duration: 2000,
          });
          // addFormVisible.value=false;
          closeDialog();
          emit('refresh');
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
}

function closeDialog() {
  addFormVisible.value = false;
  emit("closedialogevent", addFormVisible.value);
}

watch(
  () => props.FormVisible,
  (newValue) => {
    addFormVisible.value = newValue;
  }
);

onMounted(() => {
  addFormVisible.value =true
})
</script>
